package com.demo.java.net.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 多线程server端，支持多个客户端连进来，每个客户端都会占用一个线程，直到该客户端断开，线程才会消失
 *
 */
public class TestMultiClientSocketServer extends Thread {
    private Socket client;

    public TestMultiClientSocketServer(Socket c) {
        this.client = c;
    }

    public void run() {
        try {
            //这个是从客户端读取信息的
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            //这个是发信息给客户端的
            PrintWriter out = new PrintWriter(client.getOutputStream());
            // Mutil User but can't parallel

            while (true) {
                //读取客户端发来的信息
                String str = in.readLine();
                //显示读取到的信息
                System.out.println("客户端发来信息："+str);
                //返回信息给客户端
                out.println("服务器已收到你的数据!");
                out.flush();
                //end是客户端与服务器端断开连接的自定义的标识位
                if (str.equals("end"))
                    break;
            }
            //关闭相关资源，同时关闭客户端的连接
            in.close();
            out.close();
            client.close();
        } catch (IOException ex) {
        } finally {
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999);
        while (true) {
            //服务器端的accept()侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞。
            Socket client = server.accept();
            System.out.println("新客户端连接成功："+client.getInetAddress()+":"+client.getPort());
            TestMultiClientSocketServer mc = new TestMultiClientSocketServer(client);
            mc.start();
        }
    }
}
